package tests;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;

import business.Societe;

/**
 * Servlet implementation class TestAjoutSociete
 */
public class TestAjoutSociete extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public TestAjoutSociete() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**e
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// création d'une nouvelle entité Societe :
		Societe maSociete = new Societe();
		maSociete.setIdSociete(1);
		maSociete.setNomSociete("Ceci est le nom de la societe");
		maSociete.setSecteurActiviteSociete("Ceci est le secteur d'activité de la societe");
		maSociete.setDescriptifSociete("Ceci est le descriptif de la societe !");
		
		try {
			ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
			
			EntityManagerFactory entityManagerFactory = (EntityManagerFactory)context.getBean("entityManagerFactory");
			EntityManager entityManager = entityManagerFactory.createEntityManager();
			
			
			EntityTransaction tx = entityManager.getTransaction();
			tx.begin();
			
			
			entityManager.persist(maSociete);
			tx.commit();
			
			// afficher un message ajout avec succès
			
			response.setContentType("text/html");
		    PrintWriter out = response.getWriter();
		    
		    out.println("ajout d'une entité avec succès !");

			
			
		} catch (BeansException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
